package com.goldsprite.microhorigame.screens.tests.lightsystem;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.Array;
import com.goldsprite.gameframeworks.log.Debug;
import com.goldsprite.gameframeworks.screens.GScreen;
import com.goldsprite.gameframeworks.utils.math.Vector2;

public class HackLightDemo extends GScreen {
	private OrthographicCamera camera;
	private SpriteBatch batch;

	// 纹理
	private Texture groundTexture;
	private Texture playerTexture;
	private Texture libgdxTexture;
	private Texture lightTexture; // 光源纹理（圆形渐变）
	private float lightScl = 0.3f;
	private float lightIntensityScl = 1f;
	

	// 光照系统
	private DayNightLightEngine lightEngine;

	// 游戏对象位置
	private Vector2 playerCenter;
	private Array<Vector2> libgdxLogos;

	// 光源
	private HackLight playerLight;
	private Array<HackLight> ambientLights;

	// 视口尺寸
	private static final int WORLD_WIDTH = 960;
	private static final int WORLD_HEIGHT = 540;

	@Override
	public void create() {
		// 初始化相机
		camera = getCamera();

		// 初始化批处理
		batch = new SpriteBatch();

		// 加载纹理（请确保这些图片在assets目录中）
		groundTexture = new Texture("sprites/blocks/grass.png");    // 地面纹理
		playerTexture = new Texture("sprites/blocks/boss_sample.png");    // 玩家角色
		libgdxTexture = new Texture("libgdx.png");    // LibGDX logo
		lightTexture = new Texture("sprites/light2.png");      // 圆形渐变光源纹理

		// 初始化光照引擎
		lightEngine = new DayNightLightEngine(0.1f, 0.1f, 0.2f, 1f); // 深蓝色环境光

		// 初始化游戏对象
		playerCenter = new Vector2(WORLD_WIDTH / 2f, WORLD_HEIGHT / 2f);
		libgdxLogos = new Array<>();

		// 随机放置一些LibGDX logo
		for (int i = 0; i < 5; i++) {
			libgdxLogos.add(new Vector2(
				MathUtils.random(100, WORLD_WIDTH - 100),
				MathUtils.random(100, WORLD_HEIGHT - 100)
			));
		}

		// 创建光源纹理区域
		TextureRegion lightRegion = new TextureRegion(lightTexture);

		// 创建玩家跟随的光源（黄色）
		playerLight = new HackLight(lightRegion, 1f, 1f, 1f, 0.6f*lightIntensityScl, 3f * lightScl);
		playerLight.setCenter(playerCenter.x, playerCenter.y);
		lightEngine.addLight(playerLight);

		// 创建环境光源
		ambientLights = new Array<>();

		// 初始化光照引擎缓冲区
		lightEngine.createFBO(WORLD_WIDTH, WORLD_HEIGHT);

		// 设置循环速度（可选）
		lightEngine.setDayDuration(45); // 秒
	}

	@Override
	public void render(float delta) {
//		super.render(delta);

		handleInput(delta);
		update(delta);


		// 1. 开始场景捕获
		lightEngine.beginSceneCapture();
		
		//绘制背景
		drawScreenBack();

		batch.setProjectionMatrix(getCamera().combined);

		// 1. 先渲染游戏场景
		batch.begin();

		// 绘制地面（平铺）
		for (int x = 0; x < WORLD_WIDTH; x += groundTexture.getWidth()) {
			for (int y = 0; y < WORLD_HEIGHT; y += groundTexture.getHeight()) {
				batch.draw(groundTexture, x, y);
			}
		}

		// 绘制LibGDX logos
		for (Vector2 pos : libgdxLogos) {
			batch.draw(libgdxTexture, pos.x - libgdxTexture.getWidth()/2f, pos.y - libgdxTexture.getHeight()/2f);
		}

		// 绘制玩家
		batch.draw(playerTexture,
			playerCenter.x - playerTexture.getWidth()/2f,
			playerCenter.y - playerTexture.getHeight()/2f);

		batch.end();

		// 3. 结束场景捕获
		lightEngine.endSceneCapture();

		// 4. 使用光照引擎混合渲染
		lightEngine.draw(getCamera().combined, getViewport(), getClearScreenColor());

//		// 3. 可选：在光照之上渲染UI信息
//		batch.begin();
//		// 可以在这里渲染UI文字等
//		batch.end();
		
		// 更新昼夜循环
		lightEngine.updateDayNightCycle(delta);
	}

	float ticker;
	Vector2 lastPos = new Vector2();
	Color[] ranColors = new Color[]{
		Color.WHITE,
		Color.RED,
		Color.GOLD,
		Color.BLUE,
	};
	private void handleInput(float delta) {
		float speed = 400 * delta;

		if (Gdx.input.isKeyPressed(Input.Keys.W) || Gdx.input.isKeyPressed(Input.Keys.UP)) {
			playerCenter.y += speed;
		}
		if (Gdx.input.isKeyPressed(Input.Keys.S) || Gdx.input.isKeyPressed(Input.Keys.DOWN)) {
			playerCenter.y -= speed;
		}
		if (Gdx.input.isKeyPressed(Input.Keys.A) || Gdx.input.isKeyPressed(Input.Keys.LEFT)) {
			playerCenter.x -= speed;
		}
		if (Gdx.input.isKeyPressed(Input.Keys.D) || Gdx.input.isKeyPressed(Input.Keys.RIGHT)) {
			playerCenter.x += speed;
		}

		// 限制玩家在屏幕内
		playerCenter.x = MathUtils.clamp(playerCenter.x, 0, WORLD_WIDTH);
		playerCenter.y = MathUtils.clamp(playerCenter.y, 0, WORLD_HEIGHT);

		// 鼠标点击添加临时光源
		Vector2 touchPos2d = Vector2.obtain(Gdx.input.getX(), Gdx.input.getY());
		if (Gdx.input.isTouched() /*&& ticker <= 0*/ && !touchPos2d.equals(lastPos)) {
			lastPos.set(touchPos2d);
			ticker = 1/60f * 1;
			screenToViewCoord(touchPos2d, getViewport());

			TextureRegion lightRegion = new TextureRegion(lightTexture);
			Color ranColor = ranColors[(int)(Math.random() * ranColors.length)];
			HackLight tempLight = new HackLight(lightRegion,
				ranColor.r, ranColor.g, ranColor.b, ranColor.a * lightIntensityScl, 1f * lightScl);
			tempLight.setPosition(touchPos2d.x - tempLight.getWidth()/2f, touchPos2d.y - tempLight.getHeight()/2f);
			lightEngine.addLight(tempLight);
			ambientLights.add(tempLight);
		}
		ticker -= delta;
	}

	float totalDeltaTime;
	private void update(float delta) {
		// 更新玩家光源位置
		playerLight.setCenter(playerCenter.x, playerCenter.y);

		// 让环境光源有轻微的脉动效果
		totalDeltaTime += delta * 1.0f;
		float time = totalDeltaTime * 1 * (float)Math.PI;
		Debug.info("time: %s, pulse: %s", time, (MathUtils.sin(time + 0)*0.5f +0.5f) * 1f);
		
		for (int i = 0; i < ambientLights.size; i++) {
			HackLight light = ambientLights.get(i);
			float pulse = (MathUtils.sin(time + i)*0.5f +0.5f) * 1f;
			float minI = 0.3f, maxI = 1.0f;
			float minS = 0.5f, maxS = 0.7f;
			light.setAlpha((minI+lightIntensityScl * pulse) * (maxI - minI));
			light.setScale((minS+lightScl * pulse) * (maxS - minS));
		}
	}

	@Override
	public void resize(int width, int height) {
		super.resize(width, height);
	}

	@Override
	public void dispose() {
		batch.dispose();
		groundTexture.dispose();
		playerTexture.dispose();
		libgdxTexture.dispose();
		lightTexture.dispose();
		// 注意：HackLightEngine 应该添加dispose方法来释放FrameBuffer
	}
}
